# -*- coding: utf-8 -*-
# 这是一个简单MYSQL增删改查的 flask web应用
from flask import Flask, render_template, request, redirect

from web import fileutils
from web.fileutils import file_dict

fileutils.file_read()

app = Flask(__name__)
# 热更新相关参数
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True


@app.route('/')
def index():
    return render_template('/login.html')


@app.route('/login', methods=['POST', 'GET'])
def login():
    err_msg = ''

    if request.method == 'GET':
        username = request.args.get('username')
        password = request.args.get('password')

    else:
        username = request.form.get('username')
        password = request.form.get('password')

    print('username:{}, password:{}'.format(username, password))

    if username and password:
        if username == 'admin' and password == 'admin':
            return redirect('/list')
        else:
            err_msg = 'usernmae or password is wrong'
    else:
        err_msg = 'need username and password'

    return render_template('login.html', err_msg=err_msg)


@app.route('/list')
def userlist():
    userlist = file_dict.items()
    print('user list %s' % userlist)
    return render_template('list.html', userlist=userlist)


@app.route('/update')
def update():
    username = request.args.get('username')
    password = file_dict.get(username)
    user = [username, password]
    print('user: %s' % user)
    return render_template('update.html', user=user)


@app.route('/updateaction', methods=['POST', 'GET'])
def doupdate():
    params = request.args if request.method == 'GET' else request.form

    username = params.get('username')
    password = params.get('password')

    file_dict[username] = password
    fileutils.file_write()
    return redirect('/list')


@app.route('/add')
def add():
    return render_template('add.html')


@app.route('/addaction', methods=['POST', 'GET'])
def doadd():
    params = request.args if request.method == 'GET' else request.form

    username = params.get('username')
    password = params.get('password')

    if username in file_dict:
        return redirect('/list')
    else:
        file_dict[username] = password
        fileutils.file_write()
        return redirect('/list')


@app.route('/del')
def delete():
    username = request.args.get('username')
    file_dict.pop(username)
    fileutils.file_write()
    return redirect('/list')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
